import wx from 'weixin-js-sdk' // 1.2.0
import store from "@/store"
import {wechatApi} from '@/services'

/**
 * 分享给朋友
 * */
const onMenuShareAppMessage = (data)=> {
  wx.ready(function () {
    wx.onMenuShareAppMessage({
      title: data.title, // 分享标题
      desc: data.desc, // 分享描述
      link: data.link || Vue.prototype.$wechat.entryURL , // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: data.imgUrl, // 分享图标
      // type: data.type, // 分享类型,music、video或link，不填默认为link
      // dataUrl: data.info.dataUrl, // 如果type是music或video，则要提供数据链接，默认为空
      success: data.success, // 用户确认分享后执行的回调函数
      cancel: data.cancel, // 用户取消分享后执行的回调函数
    })
  })
}
/**
 * 分享到朋友圈
 * */
const onMenuShareTimeline = (data)=> {
  wx.ready(function () {
    wx.onMenuShareTimeline({
      title: data.title, // 分享标题
      link: data.link || Vue.prototype.$wechat.entryURL , // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: data.imgUrl, // 分享图标
      success: data.success, // 用户确认分享后执行的回调函数
      cancel: data.cancel, // 用户取消分享后执行的回调函数
    })
  })
}
/**
 * 微信分享入口
 * */
const weChatFX =  (data)=> {
  onMenuShareAppMessage(data)
  onMenuShareTimeline(data)
}

export class Wechat {
  constructor() {
    this.token = "" // 微信授权后的token
    this.weChatConfig = {}  // 微信配置参数
    this.ignoreShareUrls = [] // 禁止微信分享的页面
    this.location = location // 网址地址url
    this.oauthFlag = "openid" // 授权回来的?token=字段名

    this.prepayId = "" // 支付ID
    this.orderNum = "" // 支付金额
  }

  static getInstance() {
    if (!wx.instance) {
      wx.instance = new Wechat()
    }
    return wx.instance
  }

  setToken(token) {
    localStorage.setItem(this.oauthFlag, token)
    return this
  }

  getToken() {
    const token = localStorage.getItem(this.oauthFlag)
    if (token) {
      return store.state.token = token
    }
    return ""
  }

  getUrlToken() {
    const url = location.href
    const hash = location.hash
    if (url.indexOf(this.oauthFlag) > -1) {
      const token = hash.split(`?${this.oauthFlag}=`)[1]
      localStorage.setItem(this.oauthFlag, token)
      return true
    }
    return false
  }

  toOauth(url) {
    // 判断微信就跳回之前的页面
    let ua = window.navigator.userAgent.toLowerCase()
    let origin = location.origin
    // 跳转到微信授权页面
    window.location = `${origin}/renbao/wx/tz?url=/oauth/renbaoSpread`
    return
    console.log("去授权")
  }

  // 在 提交投保支付的页面 调起微信注册 mounted
  async initInRouter(data, afterConfigFun) {
    let JSsdk = await this.getConfigSign(data)
    this.weChatConfig = JSsdk
    wx.config({
      debug: false ,
      ...JSsdk,
      jsApiList: [
        'getNetworkType',
        'checkJsApi',
        'showAllNonBaseMenuItem',
        'hideAllNonBaseMenuItem',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'previewImage',
        'chooseWXPay',
        'getLocation',
        //'chooseImage',
        //'uploadImage',
        //'startRecord',
        //'stopRecord',
        //'onVoiceRecordEnd',
        //'playVoice',
        //'pauseVoice',
        //'stopVoice',
        //'onVoicePlayEnd',
        //'uploadVoice',
        //'downloadVoice',

      ]
    })

    wx.error(function (res) {
      console.warn("微信config注册失败", res)
      // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });

    afterConfigFun()
  }

  getWexinPayConfig(data) {
    return new Promise((resolve) => {
      wechatApi.createOrder(data).then(({data}) => {
        //console.log(data)
        this.prepayId = data.config.prepayId
        this.orderNum = data.order_number
        const wxConfig = data.config.json
        //console.log(wxConfig)

        const wechatPayConfig = {
          appId: wxConfig.appId,
          nonceStr: wxConfig.nonceStr,
          package: wxConfig.package,
          paySign: wxConfig.paySign,
          signType: wxConfig.signType,
          timeStamp: wxConfig.timeStamp
        }
        //console.log(wechatPayConfig)
        resolve(wechatPayConfig)
      })
    })
  }

  // 微信支付
  async doWechatPay(orderInfo, vueInstance) {
    const payParams = await this.getWexinPayConfig(orderInfo)
    this.checkWechat(()=>{
      WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, function (
        res
      ) {
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          vueInstance.payCheck()
          /*if (vueInstance.$route.query.doctor_id) {
            vueInstance.creatOrientedProblem('n')
            localStorage.removeItem('askData')
          } else {
            localStorage.removeItem('askData')
            vueInstance.creatProblem('n')
          }*/
        } else {
          /*that.$toast('支付失败')
          if (that.$route.query.doctor_id) {
            that.creatOrientedProblem('y')
            console.log('定向支付失败')
          } else {
            that.creatProblem('y')
            console.log('众包支付失败！')
          }*/
        }
      })
    })
  }

  checkWechat(onBridgeReady) {
    if(typeof WeixinJSBridge === "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
      }
    }
    else{
      onBridgeReady()
    }
  }

  doSomethingAfterWxConfig(cb) {
    const origin = location.origin // https://wx.shendu.com
    const pathname = location.pathname // /insurance/renbao/
    wechatApi.getWxSign({ url: origin + pathname }).then(res => {
      const wxConfig = res.wxConfig
      wx.config({
        debug: false ,
        ...wxConfig ,
        //...store.getters.weChatConfig, jdk
        jsApiList: [
          'getNetworkType',
          'checkJsApi',
          'showAllNonBaseMenuItem',
          'hideAllNonBaseMenuItem',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'previewImage',
          'getLocation',
          'openLocation'
          //'chooseImage',
          //'uploadImage',
          //'startRecord',
          //'stopRecord',
          //'onVoiceRecordEnd',
          //'playVoice',
          //'pauseVoice',
          //'stopVoice',
          //'onVoicePlayEnd',
          //'uploadVoice',
          //'downloadVoice',
          //'chooseWXPay'
        ]
      })
    })


    // 错误捕捉
    wx.error(() => {
      console.log('微信初始化错误，进行记录错误次数')

    })
    cb && cb()
  }

  weChatShare (data) {
    weChatFX(data)
  }

  getLocation (data) {
    const defaultData = {
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        console.log(res)
        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
        var speed = res.speed; // 速度，以米/每秒计
        var accuracy = res.accuracy; // 位置精度
      }
    }
    wx.ready(function () {
      wx.getLocation(defaultData)
    })

  }

  openLocation (){
    const defaultData = {
      latitude: 0, // 纬度，浮点数，范围为90 ~ -90
      longitude: 0, // 经度，浮点数，范围为180 ~ -180。
      name: '', // 位置名
      address: '', // 地址详情说明
      scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为最大
      infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
    }
    wx.ready(function () {
      wx.openLocation(defaultData)
    })

  }
}

